﻿/*
 * Licensed under the MIT license.
 * 
 * Copyright © 2010 Mikko Väänänen
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace ShellTail {

	class HighlightingConsoleWriter : IConsoleWriter {

		private string pattern;

		public HighlightingConsoleWriter(string pattern) {
			this.pattern = pattern;
		}

		public void Write(string text) {
			StringReader reader = new StringReader(text);
			string line;
			while ((line = reader.ReadLine()) != null) {
				WriteLine(line);
			}
		}

		private void WriteLine(string line) {
			if (ShouldHighlight(line)) {
				ConsoleColor newBgColor = Console.ForegroundColor;
				Console.ForegroundColor = Console.BackgroundColor;
				Console.BackgroundColor = newBgColor;

				Console.Write(line);
				Console.ResetColor();
				Console.WriteLine();
			} else {
				Console.WriteLine(line);
			}
		}

		private bool ShouldHighlight(string line) {
			return Regex.IsMatch(line, pattern);
		}

	}

}
